<template>
  <Form ref="formCom" v-slot="{errors}" :validation-schema="schema" class="xtx-form">
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          name="mobile"
          v-model="form.mobile"
          :class="{error:errors.mobile}"
          class="input"
          type="text"
          placeholder="绑定的手机号" />
      </div>
      <div class="error" v-if="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          name="code"
          v-model="form.code"
          :class="{error:errors.code}"
          class="input"
          type="text"
          placeholder="短信验证码" />
        <span class="code" @click="send">{{time===0 ? "发送验证码":`${time}秒后发送`}}</span>
      </div>
      <div class="error" v-if="errors.code">{{errors.code}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="loginBtn">立即绑定</a>
  </Form>
</template>

<script>
import { reactive, ref, watch } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { useIntervalFn } from '@vueuse/shared'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import Message from '@/components/library/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  components: { Form, Field },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const form = reactive({
      mobile: '',
      code: ''
    })
    const nickname = ref('')
    const avatar = ref('')
    if (QC.Login.check()) {
      QC.api('get_user_info').success(res => {
        avatar.value = res.data.figureurl_qq_1
        nickname.value = res.data.nickname
      })
    }
    const formCom = ref({})
    watch(() => props.unionId, (unionId) => {
      form.unionId = unionId
    }, { immediate: true })
    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })
    /* 1. 发送验证码
    1.1 绑定发送验证码按钮点击事件
    1.2 校验手机号，如果成功才去发送短信（定义API），请求成功开启60s的倒计时，不能再次点击，倒计时结束恢复
    1.3 如果失败，失败的校验样式显示出来 */
    const send = async () => {
      const valid = schema.mobile(form.mobile)
      if (valid === true) {
        // 上一个倒计时没有结束，直接退出
        if (time.value !== 0) return
        // 发送验证码
        try {
          await userQQBindCode(form.mobile)
          Message({ type: 'success', message: '验证码发送成功' })
          // 倒计时秒数重置
          time.value = 60
          // 调用倒计时
          resume()
        } catch (err) {
          Message({ type: 'error', message: err.response.data.message || '获取验证码出现错误' })
        }
      } else {
        // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
        console.log(formCom.value)
        formCom.value.setFieldError('mobile', valid)
      }
    }
    const store = useStore()
    const router = useRouter()
    const loginBtn = async () => {
      const valid = await formCom.value.validate()
      // console.log(valid)
      if (!valid) return Message({ type: 'error', message: '表单校验失败' })
      try {
        const { result } = await userQQBindLogin(form)
        console.log(result)
        // 1. 存储 token 信息
        store.commit('user/setUser', result)
        // 2. 页面跳转（两种情况：1.回跳到某个页面 2.跳转首页）
        // router.currentRoute.value 获取当前路由
        const redirectUrl = router.currentRoute.value.query.redirectUrl
        router.push(redirectUrl || '/')
        // 成功提示
        Message({ type: 'success', message: 'QQ登录成功' })
        // 登录成功后合并购物车数据
        store.dispatch('cart/mergeLocalCart')
      } catch (err) {
        Message({ type: 'error', message: err.response.data.message })
      }
    }

    return { nickname, avatar, formCom, form, schema, send, time, loginBtn }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
